import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

/// 开关按钮
/// [open]:是否打开
/// [leftText]:开关左侧文案
/// [rightText]:开关右侧文案
/// [checkListener]:开关点击回调
class CustomRadioWidget extends StatefulWidget {
  final bool open;
  final String leftText;
  final String rightText;
  final Function checkListener;

  CustomRadioWidget(
      {this.open = false, this.leftText = "否", this.rightText = "是", this.checkListener});

  @override
  State<StatefulWidget> createState() {
    return CustomRadioWidgetState(open);
  }
}

class CustomRadioWidgetState extends State<CustomRadioWidget> {
  final openDecoration = BoxDecoration(
      color: Color(0xFF3DBCC6),
      borderRadius: BorderRadius.all(Radius.circular(50)));
  final closeStyle = TextStyle(fontSize: 14, color: Color(0xFFCCCCCC),);
  final openStyle = TextStyle(fontSize: 14, color: Color(0xFFFFFFFF));
  bool open;

  CustomRadioWidgetState(this.open);

  @override
  void didUpdateWidget(CustomRadioWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    if(widget.open!=oldWidget.open){
      open = widget.open;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 90,
      height: 25,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Stack(
          children: <Widget>[
            Container(
                width: 50,
                height: 25,
                padding: EdgeInsets.only(bottom: 2),
                decoration: open ? null : openDecoration,
                child: Center(
                  child: Text(
                    widget.leftText,
                    textAlign: TextAlign.center,
                    style: open ? closeStyle : openStyle,
                  ),
                )),
            Positioned(
                left: 40,
                child: Container(
                    width: 50,
                    height: 25,
                    padding: EdgeInsets.only(bottom: 2),
                    decoration: open ? openDecoration : null,
                    child: Center(
                      child: Text(
                        widget.rightText,
                        textAlign: TextAlign.center,
                        style: open ? openStyle : closeStyle,
                      ),
                    )))
          ],
        ),
        onTap: () {
          open = !open;
          if (widget.checkListener != null) {
            widget.checkListener(open);
          }
          setState(() {});
        },
      ),
      decoration: BoxDecoration(
          color: Color(0xFFF0F0F0),
          borderRadius: BorderRadius.all(Radius.circular(50))),
    );
  }
}
